import React, { Component } from 'react';

class CommentInput extends Component{
  constructor(){
    super()
    this.state = {
      name: '',
      content: ''
    }
  }

  componentDidMount(){
    if(localStorage.getItem('name')){
      this.setState({
        name: localStorage.getItem('name')
      })
    }
    this.input.focus()
  }

  render(){
    return (
      <div className="comment-input">
        <div className="comment-field">
          <span className="comment-field-name">用户名：</span>
          <div className='comment-field-input'>
            <input type="text" value={this.state.name} onChange={this.nameChange.bind(this)}/>
          </div>
        </div>
        <div className='comment-field'>
          <span className='comment-field-name'>评论内容：</span>
          <div className='comment-field-input'>
            <textarea type="text" ref={input => this.input = input} value={this.state.content} onChange={this.contentChange.bind(this)} />
          </div>
        </div>
        <div className='comment-field-button'>
          <button onClick={this.submit.bind(this)}>
            发布
          </button>
        </div>
      </div>
    )
  }

  nameChange(e){
    this.setState({
      name: e.target.value
    })
    console.log(localStorage)
  }

  contentChange(e){
    this.setState({
      content: e.target.value
    })
  }

  submit(){
    let {name, content} = this.state
    if(!name){
      alert('用户名不能为空！')
      return
    }
    if(!content){
      alert('评论内容不能为空！')
      return
    }
    let createdTime = Math.round(new Date().getTime()/1000)
    localStorage.setItem('name',name)
    if(this.props.onSubmit){
      this.props.onSubmit({name, content, createdTime})
    }
    this.setState({
      content: ''
    })
  }
}

export default CommentInput